$(function() {
		$("[data-toggle='tooltip']").tooltip();
		getProductType2()
		$('.product-man-nav ul li').on("click",function(){
			var _index = $(this).index()
			$('.product-man-nav').siblings().eq(_index).show().siblings().not(":first").hide()
			$(this).children().addClass('disabled-theme').parent().siblings().children().removeClass('disabled-theme')
		})
		$('.chart-man-nav ul li').on("click",function(){
			var _index = $(this).index()
			$(this).parents(".chart-man-nav").siblings().eq(_index).show().siblings().not(":first").hide()
			$(this).children().addClass('disabled-theme').parent().siblings().children().removeClass('disabled-theme')
		})
		$('.settings-list ul li').click(function() {
			var _index = $(this).index()
			$(this).addClass('active').siblings().removeClass('active')
			$(".product").eq(_index).show().siblings().hide()
		})
//		$('#addProductDetail').siblings().first().on("click",function(){
//			var tr = "<tr><td><input type='text' class='form-control'></td><td class='col-lg-2'><select class='productSelector form-control'></select></td><td class='col-lg-5'><div class='col-lg-4'><div class='input-group'><span class='input-group-btn'><button class='btn btn-default' type='button'>大杯</button></span><input type='number' min='0' max='99' class='form-control'></div><!-- /input-group --></div><div class='col-lg-4'><div class='input-group'><span class='input-group-btn'><button class='btn btn-default' min='0' max='99' type='button'>中杯</button></span><input type='number' class='form-control'></div><!-- /input-group --></div><div class='col-lg-4'><div class='input-group'><span class='input-group-btn'><button class='btn btn-default' min='0' max='99' type='button'>小杯</button></span><input type='number' class='form-control'></div></div></td><td class='col-lg-2'><input type='text' class='form-control'></td></tr>"
//    		$("#addProductDetail").append(tr)
//    		getProductType()
//  		});
  		$('#addProType').on('change','input:last',function(){ 
			var div = "<li><div class='input-group'><input type='text' placeholder='输入商品类别名' class='form-control'><span class='input-group-btn'><button class='btn btn-default' type='button'><i class='fa fa-times' aria-hidden='true'></i></button></span></div></li>"
			$(this).parents(".modal-body #addProType").append(div)
			$(this).siblings().click(function(){
				$(this).parents(".input-group").remove()
			})
       	})
       	$('#addProductDetail').on('change','tr:last input:first',function(){ 
			var tr = "<tr><td><input type='text' class='form-control'></td><td class='col-lg-2'><select class='productSelector form-control'></select></td><td class='col-lg-5'><div class='col-lg-4'><div class='input-group'><span class='input-group-btn'><button class='btn btn-default' type='button'>大杯</button></span><input type='number' min='0' max='99' class='form-control'></div><!-- /input-group --></div><div class='col-lg-4'><div class='input-group'><span class='input-group-btn'><button class='btn btn-default' min='0' max='99' type='button'>中杯</button></span><input type='number' class='form-control'></div><!-- /input-group --></div><div class='col-lg-4'><div class='input-group'><span class='input-group-btn'><button class='btn btn-default' min='0' max='99' type='button'>小杯</button></span><input type='number' class='form-control'></div></div></td><td class='col-lg-2'><input type='text' class='form-control'><td><a href='#' onclick='deteleProductListItem(this)' class='btn btn-link' >删除</a></td></td></tr>"
			$(this).parents("#addProductDetail").find("tr:last").after(tr)
			if($('#addProductDetail tbody').children().length>1){
				$('#addProductDetail tbody').children().eq(0).find("a").removeClass("disabled")
			}
			$.ajax({ 
				type: "post",
		        url: "getProductType.action",
		        dataType: "json",
				success: function(result){
//					console.log($(this))
					$(".productSelector:last").html("")
					for(var i=0;i<result.length;i++){
						$("#addProductDetail").find(".productSelector:last").append("<option>"+result[i].name+"</option>")
					}
				},
				error:function(){
					
				}
			});
       	})
       	$('#addStaffDetail').on('change','tr:last input:first',function(){
       		var l = $(this).parents("#addStaffDetail").find("tr").length
       		var tr = "<tr><td><input type='text' class='form-control'></td><td class='col-lg-2'><label><input type='radio' checked value='男' name='staffSex"+l+"'/>男&nbsp&nbsp</label><label><input type='radio' value='女' name='staffSex"+l+"'/>女&nbsp&nbsp</label></td><td><input type='tel' placeholder='只可以输入数字'  onkeyup='onlyNum(this)' class='form-control' name=''/></td><td><input type='number' placeholder='仅输4位数字' oninput='onlyFourNum(this,"+"4"+")'  class='form-control'></td><td><input type='text' minlength='4' placeholder='仅输4位数字和英文' onkeyup='onlyNumEng(this,"+"4"+")' maxlength='4' class='form-control'></td><td class='col-lg-2'><label><input type='radio' value='admin' name='staffRole"+l+"'/>管理员</label><label><input type='radio' checked value='staff' name='staffRole"+l+"'/>普通用户</label></td><td><input type='text' class='form-control'></td><td><a href='#'  onclick='deteleProductListItem(this)'  class='btn btn-link' >删除</a></td>tr>"
			$(this).parents("#addStaffDetail").find("tr:last").after(tr)
			if($('#addStaffDetail tbody').children().length>1){
				$('#addStaffDetail tbody').children().eq(0).find("a").removeClass("disabled")
			}
       	})
  		$(".modal-body").siblings(".modal-footer").find("button").eq(0).click(function(){
				$('#addProType li').not(':first').remove()
				$('#addProType li:first').find("input").val("")
			})
//  		$(".modal-body").siblings(".modal-footer").find("button").eq(1).click(function(){
//			$('#addProType li').not(':last').each(function(){
//				$('.product-type-search').after("<div class='product-type-cell changeable' data-toggle='tooltip'  title='点击输入新的名称'><a href='#'>X</a><span>"+$(this).find("input").val()+"</span></div>")
//				$("[data-toggle='tooltip']").tooltip();
//			})
//			changeable()
//		})
//  		changeable()
  		showLeftTime()
  		
})
function showLeftTime()
{
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth();
	var day=now.getDate();
	var hours=now.getHours();
	var minutes=now.getMinutes();
	var seconds=now.getSeconds();
	if(hours<10){
		hours = "0"+minutes
	}
	if(minutes<10){
		minutes = "0"+minutes
	}
	if(seconds<10){
		seconds = "0"+seconds
	}
	$("#time").html(""+(year+1900)+"年"+month+"月"+day+"日 "+hours+":"+minutes+":"+seconds+"")
	//一秒刷新一次显示时间
	var timeID=setTimeout(showLeftTime,1000);
	
}
function changeable(arr){
//	var array.push(a)
	console.log(arr)
	$('.changeable input').off("change").on("change",function(){
		var indx = $(this).index()
		if($(this).val()!=""){
			$.ajax({ 
				type: "post",
		        url: "updateProductType.action",
		        dataType: "json",
		        data:{
		        	"type.id":$(this).attr("id"),
		        	"type.name":$(this).val()
		        },
				success: function(result){
					console.log(result)
					if(result=="更新成功"){
						alertInfo("alert-success","成功",result,"changeable")
					}
					else if(result=="该种类已存在"){
						alertInfo("alert-danger","失败",result,"changeable")
//						console.log($('.changeable input').eq(indx))
						$('.changeable input').eq(indx).val(arr[indx])
					}
				},
				error:function(){
					alertInfo("alert-danger","失败","修改失败","changeable")
				}
			})
		}
		else{
			var _index = $(this).parents('.changeable').index()
			$(this).val(arr[_index-1])
		}
	})
}
function getProductType(){
	$.ajax({ 
		type: "post",
        url: "getProductType.action",
        dataType: "json",
		success: function(result){
			$(".productSelector").html("")
			for(var i=0;i<result.length;i++){
				$(".productSelector").append("<option>"+result[i].name+"</option>")
			}
			
		},
		error:function(){
			
		}
	});
}
function addProductType(btn){
	var array = $("#addProType li input").map(function(i,v){
		if($(this).val()!=""){
			return $.trim($(this).val())
		}
	})
	var n = []; 
	for(var i = 0; i < array.length; i++){
		if (n.indexOf(array[i]) == -1) n.push(array[i]);
	}
	r = n.map(function(i,v){
		return {"producttype.name":$.trim(i)}
	})
	$.ajax({ 
		type: "post",
        url: "addProductType.action",
        dataType: "json",
        data:{
        	"inputdata":JSON.stringify(r),
        	"inputSize":r.length
        },
		success: function(result){
			result.map(function(i,v){
				$('.product-type-search').after("<div class='product-type-cell changeable' ><a onclick='deleteProductType(this)' href='#'>X</a><span data-toggle='tooltip' title='' data-original-title='点击输入新的名称' ><input value="+i+"></span></div>")
			})
			alertInfo("alert-success","成功","添加成功","addProductType")
			$('.close').click()
			$("[data-toggle='tooltip']").tooltip();
		},
		error:function(){
			
		}
	});
}
function addProduct(){
	var array = $("#addProductDetail tbody tr").not(':last').map(function(v,i){
		return {
			"product.productName" : $.trim($(this).find('input').eq(0).val()),
			"product.remark" : $.trim($(this).find('input').eq(4).val()),
			"type.name" : $.trim($(this).find('select').val()),
			"price1":$.trim($(this).find('input').eq(1).val()),
			"price2":$.trim($(this).find('input').eq(2).val()),
			"price3":$.trim($(this).find('input').eq(3).val())
		}
	})
	var msg =""
	array.map(function(i,v){
		msg = (v["product.productName"]==""&&"第"+(i+1)+"行名字没填") || (v.price1==""&&"第"+(i+1)+"行大杯价格没填") || (v.price2==""&&"第"+(i+1)+"行中杯价格没填") || (v.price3==""&&"第"+(i+1)+"行小杯价格没填"); 
//		msg?alert(msg):
	})
	if(msg){
		alert(msg+"\n")
	}
	else if(array[0]==null){
		alertInfo("alert-warning","警告","没有输入任何信息","addProduct")
	}
	else{
		$.ajax({ 
			type: "post",
	        url: "addProduct.action",
	        data: {
	        	"inputdata":JSON.stringify(array),
	        	"inputSize":array.length
	        },
	        dataType: "json",
			success: function(result){
				if(result=="增加失败"){
		    		alertInfo("alert-danger","失败",result,"addProduct")
		    	}
		    	else{
		    		alertInfo("alert-success","成功",result,"addProduct")
		    	}
				getProduct()
				$("#addProductDetail").find("input").val("")
				$("#addProductDetail tbody tr").not(':first').remove()
			},
			error:function(){
				
			}
		});
	}
}
function deteleProductListItem(a){
	if(a.tagName=="A"){
		if($(a).parents("table").children("tbody").children("tr").length<3){
			$(a).parents("table").children("tbody").children("tr").find("a").addClass("disabled")
		}
		$(a).parents("tr").remove()
	}
	else{
		$(a).parents().eq(0).find("input").not("input[type='radio']").val("")
		$(a).parents().eq(0).find("tbody tr").not(':first').remove()
		console.log($(a).prev().children("tbody").children("tr").length)
		if($(a).prev().children("tbody").children("tr").length<2){
			$(a).prev().children("tbody").children("tr").find("a").addClass("disabled")
		}
	}
}
function deleteProduct(btn){
	var prCode = $(btn).parents("tr").find("td").eq(3).text()
	$.ajax({ 
		type: "post",
        url: "deleteProduct.action",
        data: {
        	"product.productNo":prCode
        },
        dataType: "json",
		success: function(result){
			alertInfo("alert-success","成功",result,"deleteProduct")
			getProduct()
		},
		error:function(){
			alertInfo("alert-danger","失败",result,"deleteProduct")
		}
	});
}
function deleteProductType(a){
//	$(this).removeAttr("contenteditable")
//	alert("1")
	var id = $(a).siblings().find("input").attr("id")
//	console.log(name)
	$.ajax({ 
		type: "post",
        url: "deleteProductType.action",
        data: {
        	"type.id":id
        },
        dataType: "json",
		success: function(result){
//			console.log(result)
			if(result[0]=="删除成功"){
				$(a).parent().remove()
				alertInfo("alert-success","成功",result[0],"deleteProductTypey")
			}
			else{
				alertInfo("alert-danger","警告",result[0],"deleteProductTypen")
			}
		},
		error:function(result){
//			console.log(result)
			alertInfo("alert-danger","警告","删除失败!!","deleteProductType")
		}
	});
}
function getProductType2(){
	$.ajax({ 
		type: "post",
        url: "getProductType.action",
        dataType: "json",
		success: function(result){
			var array = []
			for(var i=0;i<result.length;i++){
				var div  = "<div class='product-type-cell changeable' ><a href='#' onclick='deleteProductType(this)'>X</a><span data-toggle='tooltip' title='' data-original-title='点击输入新的名称' ><input id='"+result[i].id+"' value="+result[i].name+">	</span></div>"
				$('.product-type-search').after(div)	
				array.unshift(result[i].name)
			}
			$("[data-toggle='tooltip']").tooltip();
			changeable(array)
//			var div  = "<div class='product-type-cell changeable' data-toggle='tooltip' title='' data-original-title='点击输入新的名称'><a href='javascript:deleteProductType(this)'>X</a><span style='color: rgb(255, 255, 255);'></span></div>"
//			$('.add-product-type').before(div)	
		},
		error:function(){
			
		}
	});
}
function chart(){
	$.ajax({ 
		type: "post",
        url: "getMonthForm.action",
        dataType: "json",
        data:{
        	"range":$("#yearRange").val()
        },
		success: function(result){
			for(var i=0;i<result.length;i++){
				result[i].data = result[i].data.map(function(i,v){
					return Number(i)
				})
//				console.log(result)
			}
			var mon = $("#yearRange").val()
			monSaleChart(result,mon)
		},
		error:function(){
			
		}
	});
}
function chart1(){
	if($('.beginTime').val()<$('.endTime').val()){
		$.ajax({ 
			type: "post",
	        url: "getForm.action",
	        dataType: "json",
	        data:{
	        	"begindate":$('.beginTime').val(),
	        	"enddate":$('.endTime').val()
	//        	时间格式 2017-6-1
	        },
			success: function(result){
				var name = $('.beginTime').val()+"到"+$('.endTime').val()
				for(var i=0;i<result.length;i++){
					result[i].y = Number(result[i].y)
				}
				
				proSaleChart(result,name)
			},
			error:function(){
				
			}
		});
	}
	else{
		alertInfo("alert-warning","警告","时间格式错误！","chart1")
	}
	
}
//查找商品类型
function searchProductType(input){
//	alert("1")
	var key = $(input).siblings("input").val()
	$.ajax({ 
		type: "post",
        url: "searchProductType.action",
        data:{
        	"key":key
        },
        dataType: "json",
		success: function(result){
			console.log(result)
			var arr= []
			result.map(function(v,i){
				arr.push(v.name)
			})
//			$('.product-type').find("span").eq(0).text().
			$('.product-type').children(".changeable").hide()
			$('.product-type').find("span").map(function(i){
				if((arr).indexOf($(this).find("input").val())>-1){
					$(this).parents(".changeable").show()
					$('.noResult').hide()
				}
				else if(result.length==0){
					$('.noResult').show()
				}
			})
		},
		error:function(){
			
		}
	});
}
function reductionProductType(a){
	if($(a).val()==""){
		$(".changeable").show()
		$('.noResult').hide()
	}
}
function monSaleChart(data,mon){
	var myWidth = $('.chart').width()
	var myHeight = $('.chart').height()*0.9
	$('#monSaleChart').highcharts({
        chart: {
        	width: myWidth,
        	height: myHeight,
            type: 'line'
        },
        title: {
            text: "近"+mon+'年的月销售报表'
        },
        legend: {
            itemStyle: {
                fontSize: '18px'
            }
        },
        subtitle: {
            text: '数据来源：MtPos DataBase'
        },
        xAxis: {
            categories: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
	        labels: {
	            style: {
	                fontSize: '14px'
	            }
	        }
        },
        yAxis: {
            title: {
                text: '元 (¥)',
                style: {
                	fontSize: '18px'
                }
            },	
	        labels: {
	            style: {
	                fontSize: '14px'
	            }
	        }
        },
        plotOptions: {
            line: {
                dataLabels: {
                    enabled: true          // 开启数据标签
                },
                enableMouseTracking: false // 关闭鼠标跟踪，对应的提示框、点击事件会失效
            }
        },
        series:data
    });
}
function proSaleChart(result,name){
	var myWidth = $('.chart').width()
	var myHeight = $('.chart').height()*0.9
	$('#proSaleChart').highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            width:myWidth,
            height:myHeight
        },
        subtitle: {
            text: '数据来源：MtPos DataBase'
        },
        legend: {
            itemStyle: {
                fontSize: '18px'
            }
        },
        title: {
            text: name+'产品分类销售汇总报表'
        },
        tooltip: {
            headerFormat: '{series.name}<br>',
            pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false,
                },
                showInLegend: true
            }
        },
        series: [{
            type: 'pie',
            name: '产品分类销售量占比',
            data: result
        }]
    });
}
function alertInfo(color,strong,text,sou){
	if($('.alert-position').attr("source")==sou){
		$('.alert-position').shake();
	}
	else{
		$('.alert-position').remove();
		$("body").append("<div source='"+sou+"' class='alert "+color+" alert-position'><a href='#' class='close' data-dismiss='alert'>&times;</a><strong>"+strong+"！</strong><span>"+text+"</span></div>")
	}
}
jQuery.fn.shake = function (intShakes /*Amount of shakes*/, intDistance /*Shake distance*/, intDuration /*Time duration*/) {  
    this.each(function () {  
        var jqNode = $(this);  
        for (var x = 1; x <= 3; x++) {  
            $(this).animate({ right: 3+"%" }, 40)  
            .animate({ right: 1+"%"}, 40)  
            .animate({ right: 2+"%" }, 40);
        }  
    });
    return this;  
}  
function addStaff(){
	var tr = "<tr><td><input type='text' class='form-control'></td><td class='col-lg-2'><label><input type='radio' name='staffSex'/>男&nbsp&nbsp</label><label><input type='radio' name='staffSex'/>女&nbsp&nbsp</label></td><td><input type='tel' class='form-control' name=''/></td><td><input type='number' class='form-control'></td><td><input type='text' class='form-control'></td><td class='col-lg-2'><label><input type='radio' name='staffRole'/>管理员</label><label><input type='radio' name='staffRole'/>普通用户</label></td><td><input type='text' class='form-control'></td><td><a href='javascript:void(0)'>删除</a></td></tr>"
	var flag = 0;
	$("#addStaffDetail tbody tr").not(":last").each(function(){
		if($.trim($(this).children('td').eq(0).children("input").val())!=""&&
		$.trim($(this).children('td').eq(2).children("input").val())!=""&&
		$.trim($(this).children('td').eq(3).children("input").val())!=""&&
		$.trim($(this).children('td').eq(4).children("input").val())!=""){
			flag = 1;
		}
		else{
			flag = 0;
			return false;
		}
	})
	if(flag==1){
		var array = $("#addStaffDetail tbody tr").not(":last").map(function(v,i){
			return {
				"staff.name":$.trim($(this).children('td').eq(0).children("input").val()),
				"staff.gender":$.trim($(this).children('td').eq(1).find("input:checked").val()),
				"staff.telephone":$.trim($(this).children('td').eq(2).children("input").val()),
				"staff.password":$.trim($(this).children('td').eq(4).children("input").val()),
				"staff.remark":$.trim($(this).children('td').eq(6).children("input").val()),
				"staff.staffNo":$.trim($(this).children('td').eq(3).find("input").val()),
				"staff.role":$.trim($(this).children('td').eq(5).find("input:checked").val())
			}
		})
		$.ajax({ 
			type: "post",
		       url: "addStaff.action",
		       data: {
		       	"inputdata":JSON.stringify(array),
		       	"inputSize":array.length
		       },
		       dataType: "json",
		       success: function(result){
		    	if(result=="增加失败"){
		    		alertInfo("alert-danger","失败",result,"addaddStaff")
		    	}
		    	else if(result=="员工编号已存在"){
		    		alertInfo("alert-warning","警告",result,"addaddStaff")
		    	}
		    	else{
		    		alertInfo("alert-success","成功",result,"addaddStaff")
		    	}
				/*getProduct()*/
				$("#addStaffDetail").find("input").not("input[type='radio']").val("")
				$("#addStaffDetail tbody tr").not(':first').remove()
			},
			error:function(){
				alertInfo("alert-danger","错误!","新增失败!!","addStaff")
			}
		});
	}
	else{
		alertInfo("alert-warning","警告","有必填信息为空!!","addStaff")
	}	
}
function exit(){
	var r=confirm("退出登录？?");
	if (r==true)	
	{
		window.location.href='logout.action';
	}
	else
	{
		return false;
	}
}
/*function changeStaff(a){
	console.log($(a).parents("tr"))
	var td = $(a).parents("tr").find("td")
	console.log($('td.eq(1),td.eq(3),td.eq(6),td.eq(8)'))
	$(td.eq(1)).addClass("col-xs-2").html("<input class='form-control' value="+$(td.eq(1)).text()+"></div>")
	$(td.eq(3)).html("<input class='form-control input-sm' value="+$(td.eq(3)).text()+">")
	$(td.eq(6)).html("<input class='form-control input-sm' value="+$(td.eq(6)).text()+">")
	$(td.eq(8)).html("<input class='form-control input-sm' value="+$(td.eq(8)).text()+">")
}*/










function onlyNum(a){
	a.value=a.value.replace(/\D/g,'')
}
function onlyFourNum(a,b){
	if(a.value.length>b){
		a.value=a.value.slice(0,4)
	}
}
function onlyNumEng(a,b){
	a.value=a.value.replace(/[^\w\.\/]/ig,'')
}
/*this.value=this.value.replace(/\D/g,'')
if(value.length>4)value=value.slice(0,4)
value=value.replace(/[^\w\.\/]/ig,'')*/
